package com.sx.pipeline.ui.chat

import android.app.Application
import android.net.Uri
import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.repos.http.req.CreateGroupDTO
import com.sx.pipeline.repos.http.res.ContactUserVo
import com.sx.pipeline.repos.http.res.RongGroupVO
import com.sx.pipeline.repos.http.res.RyUserVo
import com.sx.pipeline.view.treeview2.OrganizeDeptRes
import io.rong.imkit.RongIM
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.model.Conversation

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Description: TODO
 */
class ChatVM(app: Application) : CYBaseViewModel(app) {

    /**
     * 聊天分类tab
     */
    fun getChatTabsList(): List<String> {
        val tabs = mutableListOf<String>()
        tabs.add(getApplication<Application>().getString(R.string.txt_chat))
        tabs.add(getApplication<Application>().getString(R.string.txt_contact))
        return tabs
    }


    /**
     * 联系人个人信息
     */
    val contactInfoDataEvent: SingleLiveEvent<RyUserVo> = SingleLiveEvent()
    fun getRyPersonalInfo(id: Int) {
        addSubscribe(
            mModel.getRyPersonalInfo(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<RyUserVo, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: RyUserVo) {
                        contactInfoDataEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }


    /**
     * 组织架构列表
     */
    val organizeListEvent: SingleLiveEvent<List<OrganizeDeptRes>> = SingleLiveEvent()
    fun getRongOrganize() {
        addSubscribe(
            mModel.getRongOrganize()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<OrganizeDeptRes>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<OrganizeDeptRes>) {
                        organizeListEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }


    /**
     * 创建群聊
     */
    val groupSuccessEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun getCreateGroup(type: Int, name: String, userUnitIdList:List<String>) {
        val dto = CreateGroupDTO(type, name, "",userUnitIdList)
        addSubscribe(
            mModel.getCreateGroup(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: Any) {
                        groupSuccessEvent.postValue(true)
                        ToastUtils.showShort("群聊创建成功")
                        dismissLoadingDialog()
                        getRongGroupListOne{
                            ARouter.getInstance().build(RoutePath.Chat.CHAT_GROUP).navigation()
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }

    var imId = SingleLiveEvent<Int>()
    fun intentService(){
        addSubscribe(mModel.getAppServiceId()
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(object : CommonObserver<ContactUserVo,BaseViewModel<*>>(this,true){
                override fun onResult(result: ContactUserVo) {
                    dismissLoadingDialog()
                    val userInfo = io.rong.imlib.model.UserInfo(
                        result.userUnitId.toString(),
                        result.userName,
                        Uri.parse(result.avatar)
                    )
                    RongIM.getInstance().refreshUserInfoCache(userInfo)
                    imId.postValue(result.userUnitId)
                }

                override fun onFailed(code: Int, msg: String?) {
                    super.onFailed(code, msg)
                    ToastUtils.showShort(msg)
                    dismissLoadingDialog()
                }

            })
        )
    }

    fun getRongGroupListOne(refreshSuccess:(()->Unit)) {
        addSubscribe(
            mModel.getRongGroupList()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<RongGroupVO>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<RongGroupVO>) {

                        refreshRongGroupInfo(result,refreshSuccess)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )

    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>,refreshSuccess:(()->Unit)) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
        refreshSuccess.invoke()
    }


}